package com.schoolvisitors;

import com.schoolvisitors.entity.Reservation;
import com.schoolvisitors.entity.TimeSlot;
import com.schoolvisitors.entity.User;
import com.schoolvisitors.enums.ReservationStatusEnum;

import com.schoolvisitors.repository.ReservationRepository;
import com.schoolvisitors.repository.UserRepository;
import com.schoolvisitors.service.CubicleService;
import com.schoolvisitors.service.ReservationService;
import com.schoolvisitors.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class AutoCheckInTimeoutTask {


    private final ReservationRepository reservationRepository;
    private final CubicleService cubicleService;
    private final ReservationService reservationService;
    private final WeChatService weChatService;
    private final UserRepository userRepository;

    @Autowired
    public AutoCheckInTimeoutTask(ReservationRepository reservationRepository, CubicleService cubicleService, ReservationService reservationService, WeChatService weChatService, UserRepository userRepository){
        this.reservationRepository = reservationRepository;
        this.cubicleService = cubicleService;
        this.reservationService = reservationService;
        this.weChatService = weChatService;
        this.userRepository = userRepository;
    }


    @Scheduled(cron = "0 */1 * * * ?") // 每1分钟执行一次
    @Transactional
    public void markNoShowReservations() {
        LocalDateTime now = LocalDateTime.now();

        // 审核通过但未签到的预约 标记未签到
        List<Reservation> approvedReservations = reservationRepository.findByStatusAndNotOutWarnAndDateLessThanEqual(ReservationStatusEnum.APPROVED, false, LocalDate.now());

        for (Reservation reservation : approvedReservations) {
            TimeSlot timeSlot = reservation.getTimeSlot();
            if (timeSlot == null) continue;

            LocalDateTime startTime = LocalDateTime.of(reservation.getDate(), timeSlot.getStartTime());
            LocalDateTime endTime = LocalDateTime.of(reservation.getDate(), timeSlot.getEndTime());

            // 查询是否签到/签退
            boolean checkIn = reservation.getCheckInTime() != null;
            boolean checkOut = reservation.getCheckOutTime() != null;

            // 未签到且超过预约开始时间+10分钟
//            if (checkIn == null && now.isAfter(startTime.plusMinutes(10))) {
//                reservation.setStatus(ReservationStatusEnum.NO_SHOW);
//                cubicleReservationRepository.save(reservation);
//            }

            // 未签退，且已过结束时间+30分钟
            if (!checkOut && now.isAfter(endTime.plusMinutes(30))) {
                User user = reservation.getUser();
                System.out.println("[警告] 用户ID " + reservation.getUser().getId() + " 的预约ID " + reservation.getId() + " 已超时未签退！");

                weChatService.sendTextMessage(user.getWechatUserId(), "[提示] 你有一个" + reservation.getDate() + " 的预约未签退, 已被取消预约权限, 请联系管理员");
                reservation.setNotOutWarn(true);
                reservationRepository.save(reservation);
                user.setReservationPermission(false);
                userRepository.save(user);
                //

            }
        }

        // 待审核但预约结束时间已过 标记为未通过
        List<Reservation> pendingReservations = reservationRepository.findByStatusAndDateLessThanEqual(ReservationStatusEnum.PENDING, LocalDate.now());
        for (Reservation reservation : pendingReservations) {
            TimeSlot timeSlot = reservation.getTimeSlot();
            if (timeSlot == null) continue;

            LocalDateTime endTime = LocalDateTime.of(reservation.getDate(), timeSlot.getEndTime());

            if (now.isAfter(endTime)) {
                log.info("自动未通过: {}", reservation.getId());
                reservationService.rejectReservation(reservation.getId());
            }
        }
    }
}
